package com.tuniu.agents.common.client;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class OpenAIHttpClient {

    private final HttpClient httpClient;
    private final ObjectMapper objectMapper;

    @Value("${spring.ai.openai.api-key}")
    private String apiKey ;
    @Value("${spring.ai.openai.base-url}/v1/chat/completions")
    private String apiUrl ;

    public OpenAIHttpClient() {
        this.httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        this.objectMapper = new ObjectMapper();
    }

    public String sendRequest(String systemPrompt, String prompt,String modelName) {
        return sendRequestForImage(systemPrompt, prompt, null,modelName);
    }

    public String sendRequestForImage(String systemPrompt, String prompt, String imageBase64,String modelName) {
        modelName = modelName == null ? "qwen2.5-vl-32b-instruct" : modelName;
        try {
            List<Map<String, Object>> systemContent = new ArrayList<>();
            systemContent.add(Map.of("type", "text", "text", systemPrompt));

            List<Map<String, Object>> content = new ArrayList<>();
            content.add(Map.of("type", "text", "text", prompt));

            Map<String, Object> systemMessage = Map.of(
                "role", "system",
                "content", systemContent
            );

            Map<String, Object> userMessage = Map.of(
                "role", "user",
                "content", content
            );

            if (imageBase64 != null && !imageBase64.isEmpty()) {
                content.add(
                    Map.of(
                        "type", "image_url",
                        "image_url", Map.of("url", "data:image/jpeg;base64," + imageBase64)
                    )
                );
            }

            Map<String, Object> requestBody = Map.of(
                "model", modelName,
                "messages", new Object[]{systemMessage, userMessage}
            );

            String jsonBody = objectMapper.writeValueAsString(requestBody);

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(apiUrl))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(jsonBody))
                    .build();

            log.info("Sending request to OpenAI API with system prompt: {} and prompt: {}", systemPrompt, prompt);

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            
            log.info("Received response from OpenAI API: {}", response.body());
            
            if (response.statusCode() != 200) {
                throw new RuntimeException("OpenAI API returned non-200 status code: " + response.statusCode());
            }

            OpenAIResponse openAIResponse = objectMapper.readValue(response.body(), OpenAIResponse.class);
            
            if (openAIResponse.getChoices() == null || openAIResponse.getChoices().isEmpty()) {
                throw new RuntimeException("No response choices available");
            }

            return openAIResponse.getChoices().get(0).getMessage().getContent();
            
        } catch (Exception e) {
            log.error("Error sending request to OpenAI API", e);
            throw new RuntimeException("Failed to send request to OpenAI API", e);
        }
    }
} 